<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

use Log;
use Overtrue\EasySms\EasySms;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
use Overtrue\EasySms\Strategies\OrderStrategy;

class SendMobileSms implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $sms;

    public $sms_config;

    /**
     * Create a new job instance.
     * 阿里云短信
     *
     */
    public function __construct($sms)
    {
        $this->sms = $sms;

        $this->sms_config = [
            // HTTP 请求的超时时间（秒）
            'timeout' => 5.0,

            // 默认发送配置
            'default' => [
                // 网关调用策略，默认：顺序调用
                'strategy' => OrderStrategy::class,

                // 默认可用的发送网关
                'gateways' => [
                    'aliyun',
                ],
            ],
            // 可用的网关配置
            'gateways' => [
                'errorlog' => [
                    'file' => storage_path('/logs/easy-sms.log'),
                ],
                'aliyun' => [
                    'access_key_id' => 'LTAIjxXq7WXMIz3a',
                    'access_key_secret' => 'RI2bkGGQJOuNY7W1FP7s5ubvzv6Z2p',
                    'sign_name' => '加电侠',
                ]
            ],
        ];
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $sms = clone $this->sms;
        try {

            $template = '';
            if ($sms->content_type == 'register') {
                $template = 'SMS_125020205';
            } else if ($sms->content_type == 'password_reset') {
                $template = 'SMS_125115298';
            }

            $easy_sms = new EasySms($this->sms_config);
            $resp = $easy_sms->send($sms->mobile, [
                'content' => $sms->content,
                'template' => $template,
                'data' => [
                    'code' => $sms->code
                ]
            ]);

            $this->sms->status = 1;
            $this->sms->save();

            Log::debug('发送短信验证码', [$sms->mobile, $sms->content, $sms->updated_at, $resp]);
        } catch (NoGatewayAvailableException $exception) {
            $this->sms->status = 2;
            $this->sms->remark = '暂无可用短信发送网关，请确保各短信平台余额充足！';
            $this->sms->save();
            Log::error('短信发送服务异常', [$this->sms, $exception->results, $exception->getMessage(), $exception->getFile(), $exception->getLine()]);
        } catch (\Throwable $exception) {
            $this->sms->status = 2;
            $this->sms->remark = $exception->getMessage();
            $this->sms->save();
            Log::error('短信发送服务异常', [$this->sms, $exception->getMessage(), $exception->getFile(), $exception->getLine()]);
        }
    }
}
